<template>
  <div class="container">
    <el-form ref="formRef" :model="form" :rules="rules" v-loading="loading" label-width="150px">
      <el-divider content-position="left"><span class="title-left-color">基本信息</span></el-divider>
      <el-row :gutter="10">
        <el-col :span="10">
          <el-form-item label="模板名称：" prop="deliver_name">
            <el-input v-model.trim.number="form.deliver_name" placeholder="请输入运费模板"> </el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-divider content-position="left"><span class="title-left-color">配送区域及运费 </span></el-divider>
      <div class="handle-box">
        <el-button type="primary" :icon="Plus" class="mb10" :disabled="disabledbtn" @click="handleAddDeliverData">新增</el-button>
      </div>
      <el-table :data="form.regionArray" border class="table" ref="formRegionArray" :reserve-selection="true">
        <el-table-column type="index" align="center"> </el-table-column>
        <el-table-column prop="deliver_name" label="可配送区域" align="center">
          <template #default="scope">
            <div class="">
              <div>{{ scope.row.provinceName }}</div>
              <div class="">
                <el-button type="primary" link :icon="Plus" v-if="scope.row.provinceName === ''" @click="handleAddProvince(scope.$index)">添加</el-button>
                <el-button type="primary" link :icon="EditPen" v-else @click="handleEditProvince(scope.$index, scope.row)">编辑</el-button>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="first_unit" label="首件（个）" align="center">
          <template #default="scope">
            <el-input v-model.number.trim="scope.row.first_unit" placeholder="请输入内容"></el-input>
          </template>
        </el-table-column>
        <el-table-column prop="first_price" label="首费（元）" align="center">
          <template #default="scope">
            <el-input v-model.trim="scope.row.first_price" placeholder="请输入内容"></el-input>
          </template>
        </el-table-column>
        <el-table-column prop="renew_unit" label="续件（个）" align="center">
          <template #default="scope">
            <el-input v-model.number.trim="scope.row.renew_unit" placeholder="请输入内容"></el-input>
          </template>
        </el-table-column>
        <el-table-column prop="renew_price" label="续费（元）" align="center">
          <template #default="scope">
            <el-input v-model.trim="scope.row.renew_price" placeholder="请输入内容"></el-input>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" align="center">
          <template #default="scope">
            <div class="mlr10 display-inline-block">
              <el-popconfirm placement="top" width="160" title="你确定要删除吗?" @confirm="deleteAegionArrayRow(scope.$index)">
                <template #reference>
                  <el-button link :icon="Delete" type="danger">删除</el-button>
                </template>
              </el-popconfirm>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </el-form>
    <div class="footer-center">
      <el-button :disabled="disabledbtn" @click="cancelSubmit">取 消</el-button>
      <el-button type="primary" :disabled="disabledbtn" v-if="!isDisabledbtn" @click="submitForm">确 定</el-button>
    </div>
    <!-- 配送区域 -->
    <ProvinceDialog :provinceSelectList="provinceSelectList" v-model:editVisible="editVisible" v-model:checkedProvinces="checkedProvinces" v-model:checkAll="checkAll" @submitSelectProvince="submitSelectProvince" />
  </div>
</template>

<script setup lang="ts">
import { EditPen, Delete, Plus } from "@element-plus/icons-vue";
import type { postOrPutType } from "@/constants";
import type { HasId, ViewMode } from "@/types/common";
import ProvinceDialog from "@/components/redPacketMallManage/FreighTemplate/ProvinceDialog.vue";
import { useState } from "@/hooks/useState.ts";
import type { IMallDeliverDTO, IRegionItem } from "@/types/redPacketMallManage/mallDeliver";
import { commonMallDeliverInfo, getMallDeliverByIdInfo } from "@/utils/api/mallDeliver";
import type { IRegion, ISearchRegion } from "@/types/redPacketMallManage/region";
import { getRegionInfo } from "@/utils/api/region";
const { disabledbtn, loading, toggleState } = useState();
interface Props {
  id: number;
}
const { id } = defineProps<Props>();
const formStatus = defineModel<ViewMode>("formStatus", { required: true });

const emit = defineEmits<{
  handleInitData: [];
  handleSuccess: [];
}>();

const isDisabledbtn = ref(false);
const editVisible = ref(false);
const checkAll = ref(false);
/* 选中可配送区域及运费数组中的第几项 index */
const selectIndex = ref(-1);
const provinceList = ref<Array<IRegion>>([]);
const provinceSelectList = ref<Array<IRegion>>([]);
const checkedProvinces = ref<Array<number>>([]);
const formRef = useTemplateRef("formRef");
const methodType = ref<postOrPutType>("PUT");
const form = reactive<IMallDeliverDTO>({
  id: 0,
  deliver_name: "",
  regionArray: []
});
const rules = reactive({
  deliver_name: [{ required: true, message: "请填写模板名称", trigger: "blur" }]
});

onMounted(() => {
  console.log("Component mounted!");
});

/* formStatus处理器 */
const statusHandlers: Record<ViewMode, () => void> = {
  view: () => {
    isDisabledbtn.value = true;
  },
  edit: () => {
    methodType.value = "PUT";
  },
  add: () => {
    methodType.value = "POST";
  },
  none: () => {
    /* 初始化数据 */
    handleInitData();
  }
};
/* 监听formStatus,新增，编辑，查看的时候都可以打开模态框，又是有不同的操作和效果，需要单独判断，none为模态框关闭的情况，需要初始化数据 */
watch(formStatus, newValue => {
  const handler = statusHandlers[newValue];
  handler?.();
});
/*  */
watch(
  () => id,
  newValue => {
    if (newValue == 0) {
      /* 初始化数据 */
    } else {
      form.id = newValue;
      handleGetMallDeliverByIdInfo(id);
    }
  }
);
/* 获取省 地址信息 */
function handleGetRegionInfo() {
  getRegionInfo<IRegion, ISearchRegion>({ parent_id: 0 })
    .then(res => {
      provinceList.value = ([] as IRegion[]).concat(res.result);
      provinceSelectList.value = ([] as IRegion[]).concat(res.result);
    })
    .catch(() => {});
}

/* 获取运费模板详情信息 */
function handleGetMallDeliverByIdInfo(id: number) {
  toggleState(true);
  getMallDeliverByIdInfo<IMallDeliverDTO, HasId>({ id })
    .then(res => {
      form.id = res.result.id;
      form.deliver_name = res.result.deliver_name;
      form.regionArray = ([] as IRegionItem[]).concat(res.result.regionArray);
      /* 删除已经选过的省 */
      let idArray = res.result.regionArray.map(item => item.regions.map(arr => arr));
      let array: Array<number> = [];
      idArray.forEach(item => {
        array = [...array, ...item];
      });
      provinceSelectList.value = provinceSelectList.value.filter((item: IRegion) => array.lastIndexOf(item.id) < 0);
      handleSelectProvinceFormet();
    })
    .catch(() => {})
    .finally(() => {
      toggleState(false);
    });
}

/* 获取选中的省 格式化 */
function handleSelectProvinceFormet() {
  form.regionArray = form.regionArray.filter(item => {
    let provinceNameArray = [];
    for (let i = 0; i < item.regions.length; i++) {
      if (item.regions.length === provinceList.value.length) {
        provinceNameArray.push("全国");
        break;
      }
      for (let j = 0; j < provinceList.value.length; j++) {
        if (provinceList.value[j].id === item.regions[i]) {
          provinceNameArray.push(provinceList.value[j].name);
          break;
        }
      }
    }
    item.provinceName = provinceNameArray.join(",");
    return item;
  });
}

/* 新增 可配送区域及运费地址 */
function handleAddDeliverData() {
  /* 判断是否所有地区都有了 */
  let num = 0;
  for (let i = 0; i < form.regionArray.length; i++) {
    num += form.regionArray[i].regions.length;
  }
  if (num === provinceList.value.length) {
    ElMessage.warning("你已经选择了所有区域,无需再新增了");
    return;
  }
  /* 添加新的配送区域及运费记录 */
  let regionObj = {
    id: -1,
    first_price: 0,
    first_unit: 0,
    provinceName: "",
    regions: [],
    renew_price: 0,
    renew_unit: 0
  };
  form.regionArray.push(regionObj);
}

/* 新增地址 */
function handleAddProvince(index: number) {
  selectIndex.value = index;
  editVisible.value = true;
  /* 修改可选择的省份 */
  /* 删除已经选过的省 ，自己除外 */
  let idArray = form.regionArray.map(item => item.regions.map(arr => arr));
  let array: Array<number> = [];
  idArray.forEach(item => {
    array = [...array, ...item];
  });
  provinceSelectList.value = provinceList.value.filter((item: IRegion) => array.lastIndexOf(item.id) < 0);
}
/* 编辑地址 */
function handleEditProvince(index: number, row: IRegionItem) {
  selectIndex.value = index;
  editVisible.value = true;
  /* 修改可选择的省份 */
  /* 删除已经选过的省 ，自己除外 */
  let idArray = form.regionArray.map(item => item.regions.map(arr => arr));
  let array: Array<number> = [];
  for (let i = 0; i < idArray.length; i++) {
    if (i !== index) {
      array = [...array, ...idArray[i]];
    }
  }
  provinceSelectList.value = provinceList.value.filter(item => array.lastIndexOf(item.id) < 0);
  /* 获取已经选中的省 */
  checkedProvinces.value = row.regions;
  /* 修改全选与部分选 的样式 */
  handleCheckAll(checkedProvinces.value.length, provinceSelectList.value.length);
}
/* 修改全选与部分选 的样式 */
function handleCheckAll(checkedCount: number, selectListLength: number) {
  checkAll.value = checkedCount === selectListLength;
}
/* 删除可配送区域及运费地址*/
function deleteAegionArrayRow(index: number) {
  form.regionArray.splice(index, 1);
  checkedProvinces.value = [];
  checkAll.value = false;
}
/* 确定选择省 */
function submitSelectProvince() {
  form.regionArray[selectIndex.value].regions = ([] as number[]).concat(checkedProvinces.value);
  handleSelectProvinceFormet();
}

/* 初始化数据 */
function handleInitData() {
  methodType.value = "POST";
  isDisabledbtn.value = false;

  checkAll.value = false;

  form.id = 0;
  form.regionArray = [];

  formRef.value?.resetFields();
  formRef.value?.clearValidate();
}

/* 保存校验数据 */
function handleValidate() {
  if (form.regionArray.length === 0) {
    ElMessage.warning("请新增配送区域及运费信息");
    return false;
  }
  let num = 0;
  for (let i = 0; i < form.regionArray.length; i++) {
    num += form.regionArray[i].regions.length;
  }
  if (num !== provinceList.value.length) {
    ElMessage.warning("还有未添加的省份，请添加");
    return false;
  }
  return true;
}

/* 删除没有存地址的数据 */
function handleNullAddress() {
  let i = form.regionArray.length;
  while (i--) {
    if (form.regionArray[i].regions.length === 0) form.regionArray.splice(i, 1);
  }
}

/* 保存或编辑 */
function submitForm() {
  if (!formRef.value) return;
  formRef.value.validate(valid => {
    if (!valid) {
      ElMessage.warning("请填写必填字段");
      return;
    }
    if (!handleValidate()) return;
    /* 删除没有存地址的数据 */
    handleNullAddress();
    submitFormInfo();
  });
}

/* 保存或编辑信息 */
function submitFormInfo() {
  /* 防止多次提交 */
  toggleState(true);
  commonMallDeliverInfo(form, methodType.value)
    .then(res => {
      ElMessage.success(res.msg);
      cancelSubmit();
      emit("handleSuccess");
    })
    .catch(() => {})
    .finally(() => {
      toggleState(false);
    });
}
/* 保存或编辑 取消提交 */
function cancelSubmit() {
  // clearData();
  // activeName = "one";
  emit("handleInitData");
}

handleGetRegionInfo();
</script>

<style lang="scss" scoped>
/* 修改select的盒模型 */
.el-select {
  display: block;
}
/* 底部按钮居中 */
.footer-center {
  margin: 10px 0;
  text-align: center;
}
</style>
